package dp;
//todo memory out
public class ShortestPalindrome214 {
    public String shortestPalindrome(String s) {
        boolean[][] dp = new boolean[s.length()][s.length()];
        for (int i = 0; i < s.length(); i++) {
            dp[i][i] = true;
        }
        for (int i = 0; i < s.length() - 1; i++) {
            if(s.charAt(i)==s.charAt(i+1)){
                dp[i][i+1] = true;
            }
        }
        for (int i = 2; i < s.length(); i++) {
            for (int j = 0; j < s.length()-i;j++) {
                if(s.charAt(j)==s.charAt(j+i)&&dp[j+1][j+i-1]){
                    dp[j][j+i] = true;
                }
            }
        }

        int max = -1;
        for (int i = 0; i < s.length(); i++) {
            if(dp[0][i]&&i>max){
                max = i;
            }
        }
        String substring = s.substring(max + 1);
        StringBuilder sb = new StringBuilder(substring);
        sb.reverse();
        sb.append(s);
        return sb.toString();
    }
}
